from masonite.controllers import Controller
from masonite.views import View
from masonite.request import Request
from masonite.response import Response
from app.traits.MyControllerTrait import MyControllerTrait
from app.traits.MyModelTrait import MyModelTrait
from app.models.AdminUser import AdminUser
from app.models.AdminRole import AdminRole
from masonite.facades import Session
from app.models.AdminActionLog import AdminActionLog
from app.my_package.MyPackage import MyValidator


class AdminUserController(Controller):
    uri = '/admin/user'
    temp = "admin.user"

    def index(self, view: View):
        uri  = self.uri + '/index'
        data = {
            'uri': self.uri,
            'uri2': "/admin/bind-role",
            'menus': MyControllerTrait.get_menu_nav(uri),
            'title': MyControllerTrait.get_permission_title(uri)
        }
        return view.render(self.temp + ".index", data)

    def show(self, request: Request, response: Response, view: View):
        account = request.input("account")
        page    = request.input("page", 1)
        limit   = request.input("limit", 10)

        table = AdminUser.get_table_name()
        where = ''
        order = 'id DESC'
        if len(account) > 0:
            where = 'account = %{0}%'.format(account)

        total, admin_users = MyModelTrait.search_for_show(table, where, '*', page, limit, order)
        if admin_users is not None:
            for index, admin_user in enumerate(admin_users):
                role_name = '-'
                admin_role = AdminRole.where('id', admin_user['admin_role_id']).first()
                if admin_role is not None:
                    role_name = admin_role['title']

                admin_users[index]['admin_role_id'] = role_name
                admin_users[index]['is_lock'] = AdminUser.FIELDS['is_lock'][admin_user['is_lock']]
                admin_users[index]['created_at'] = MyControllerTrait.time_format_conversion(admin_user['created_at'])
                admin_users[index]['updated_at'] = MyControllerTrait.time_format_conversion(admin_user['updated_at'])
                del admin_users[index]['password']
                del admin_users[index]['salt']
                del admin_users[index]['is_deleted']

        return response.json({'code': 0, 'message': 'success', 'data': admin_users})

    def create(self, view: View):
        data = {'uri': self.uri}
        return view.render(self.temp + '.create', data)

    def store(self, request: Request, response: Response):
        account  = request.input("account")
        password = request.input('password')
        nickname = request.input('nickname')
        is_lock  = request.input('is_lock')

        b, m = MyValidator.boolean(is_lock)
        if b is False:
            return response.json({'code': 0, 'message': '锁定' + m})
        b, m = MyValidator.alpha_num(account)
        if b is False:
            return response.json({'code': 0, 'message': '账户' + m})
        b, m = MyValidator.between(account, 5, 15)
        if b is False:
            return response.json({'code': 0, 'message': '账户' + m})
        b, m = MyValidator.alpha_num(password)
        if b is False:
            return response.json({'code': 0, 'message': '密码' + m})
        b, m = MyValidator.between(password, 5, 15)
        if b is False:
            return response.json({'code': 0, 'message': '密码' + m})
        b, m = MyValidator.ch_alpha_num(nickname)
        if b is False:
            return response.json({'code': 0, 'message': '昵称' + m})
        b, m = MyValidator.between(nickname, 2, 15)
        if b is False:
            return response.json({'code': 0, 'message': '昵称' + m})

        admin_user = AdminUser.where('account', account).first()
        if admin_user is not None:
            return response.json({'code': 0, 'message': '账户 {0} 已存在'.format(account)})

        salt = MyModelTrait.generate_salt(6)
        password = MyModelTrait.generate_password(password, salt)
        AdminUser.generate_log(account, password, salt, nickname, 0, int(is_lock), 0)
        remark = MyControllerTrait.get_permission_title(request.get_path()) + ":{0}".format(account)
        AdminActionLog.generate_log(Session.get('admin_user')['id'], request.get_path(), request.ip(), remark)
        return response.json({'code': 1, 'message': '成功'})

    def edit(self, request: Request, response: Response, view: View):
        admin_user_id = request.input("id")
        b, m = MyValidator.is_integer(int(admin_user_id))
        if b is False:
            return response.redirect(location=self.uri+'/index', status=302)

        admin_user = AdminUser.where('id', admin_user_id).first()
        if admin_user is None:
            return response.redirect(location=self.uri + '/index', status=302)
        data = {
            'uri': self.uri,
            'data': admin_user
        }

        return view.render(f"{self.temp}.edit", data)

    def edit2(self, request: Request, response: Response, view: View):
        admin_user_id = Session.get('admin_user')['id']
        admin_user = AdminUser.where('id', admin_user_id).first()
        if admin_user is None:
            return response.redirect(location=self.uri + "/index", status=302)

        data = {
            'uri': self.uri,
            'data': admin_user,
            'menus': MyControllerTrait.get_menu_nav(self.uri + '/edit2'),
            'title': '编辑资料'
        }
        return view.render(self.temp + ".edit2", data)

    def update(self, request: Request, response: Response):
        id = request.input("id")
        password = request.input("password")
        nickname = request.input("nickname")
        is_lock = request.input("is_lock")

        b, m = MyValidator.is_integer(int(id))
        if b is False:
            return response.json({'code': 0, 'message': 'id' + m})
        b, m = MyValidator.boolean(int(is_lock))
        if b is False:
            return response.json({'code': 0, 'message': '锁定' + m})
        b, m = MyValidator.ch_alpha_num(nickname)
        if b is False:
            return response.json({'code': 0, 'message': '昵称' + m})
        b, m = MyValidator.between(nickname, 2, 15)
        if b is False:
            return response.json({'code': 0, 'message': '昵称' + m})

        if len(password) > 0:
            b, m = MyValidator.alpha_num(password)
            if b is False:
                return response.json({'code': 0, 'message': '密码' + m})
            b, m = MyValidator.between(password, 5, 15)
            if b is False:
                return response.json({'code': 0, 'message': '密码' + m})

        admin_user = AdminUser.where('id', id).first()
        if admin_user is None:
            return response.json({'code': 0, 'message': '未知账户'})

        data = {}
        if len(password) > 0:
            data['password'] = MyModelTrait.generate_password(password, admin_user.salt)

        data['nickname'] = nickname
        data['is_lock'] = is_lock
        admin_user.update(data)
        remark = MyControllerTrait.get_permission_title(request.get_path()) + ":id:{0},{1}".format(admin_user.id, admin_user.account)
        AdminActionLog.generate_log(Session.get('admin_user')['id'], request.get_path(), request.ip(), remark)
        return response.json({'code': 1, 'message': '成功'})

    def update2(self, request: Request, response: Response):
        password = request.input("password")
        nickname = request.input("nickname")
        is_lock = request.input("is_lock")
        id = Session.get('admin_user')['id']

        b, m = MyValidator.boolean(int(is_lock))
        if b is False:
            return response.json({'code': 0, 'message': '锁定' + m})
        b, m = MyValidator.ch_alpha_num(nickname)
        if b is False:
            return response.json({'code': 0, 'message': '昵称' + m})
        b, m = MyValidator.between(nickname, 2, 15)
        if b is False:
            return response.json({'code': 0, 'message': '昵称' + m})

        if len(password) > 0:
            b, m = MyValidator.alpha_num(password)
            if b is False:
                return response.json({'code': 0, 'message': '密码' + m})
            b, m = MyValidator.between(password, 5, 15)
            if b is False:
                return response.json({'code': 0, 'message': '密码' + m})

        admin_user = AdminUser.where('id', id).first()
        if admin_user is None:
            return response.json({'code':0, 'message':'未知用户'})

        data = {}
        if admin_user.is_lock != int(is_lock):
            data['is_lock'] = is_lock
        if admin_user.nickname != nickname:
            data['nickname'] = nickname
        if len(password) > 0:
            salt = MyModelTrait.generate_salt(6)
            data['password'] = MyModelTrait.generate_password(password, salt)
            data['salt'] = salt

        if len(data) > 0:
            admin_user.update(data)
        remark = "管理员信息编辑:" + admin_user.account
        AdminActionLog.generate_log(Session.get('admin_user')['id'], request.get_path(), request.ip(), remark)
        return response.json({'code': 1, 'message': '成功'})

    def destroy(self, request: Request, response: Response):
        id = request.input("id")
        b, m = MyValidator.is_integer(int(id))
        if b is False:
            return response.json({'code': 0, 'message': 'id' + m})

        admin_user = AdminUser.where('id', id).first()
        if admin_user is None:
            return response.json({'code': 0, 'message': '未知管理员'})
        if admin_user.id == int(id):
            return response.json({'code': 0, 'message': '无法删除自身'})
        if AdminUser.is_super_admin(admin_user.account):
            return response.json({'code': 0, 'message': '无法删除超级管理员账户'})

        remark = MyControllerTrait.get_permission_title(request.get_path()) + ":{0}".format(admin_user.account)
        AdminActionLog.generate_log(Session.get('admin_user')['id'], request.get_path(), request.ip(), remark)
        admin_user.delete()
        return response.json({'code': 1, 'message': '成功'})